<template>
  <div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
    <!-- 背景装饰 -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none">
      <div class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob"></div>
      <div class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000"></div>
      <div class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="container mx-auto px-12 py-10 pt-32 relative z-10">
      <!-- 顶部：返回与标题 -->
      <div class="flex items-center justify-between mb-10">
        <div class="flex items-center gap-4">
          <el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
            <el-icon class="mr-2 text-xl"><ArrowLeft /></el-icon>
            返回班级详情
          </el-button>
          <h1 class="text-4xl font-bold text-gray-900">发布作业</h1>
        </div>
        <div class="flex items-center gap-4">
          <el-button type="primary" size="large" @click="showSubmitDialog = true" class="rounded-full px-6">
            <el-icon class="mr-2"><Plus /></el-icon>
            发布作业
          </el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200">
          <div class="flex items-center gap-4">
            <div class="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center">
              <el-icon class="text-blue-600 text-2xl"><Document /></el-icon>
            </div>
            <div>
              <p class="text-2xl font-bold text-gray-900">{{ homeworkStats.total }}</p>
              <p class="text-gray-600">总作业数</p>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200">
          <div class="flex items-center gap-4">
            <div class="w-16 h-16 bg-green-100 rounded-xl flex items-center justify-center">
              <el-icon class="text-green-600 text-2xl"><Check /></el-icon>
            </div>
            <div>
              <p class="text-2xl font-bold text-gray-900">{{ homeworkStats.ungraded }}</p>
              <p class="text-gray-600">未批改</p>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200">
          <div class="flex items-center gap-4">
            <div class="w-16 h-16 bg-yellow-100 rounded-xl flex items-center justify-center">
              <el-icon class="text-yellow-600 text-2xl"><Clock /></el-icon>
            </div>
            <div>
              <p class="text-2xl font-bold text-gray-900">{{ homeworkStats.published }}</p>
              <p class="text-gray-600">已发布</p>
            </div>
          </div>
        </div>
        <div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200">
          <div class="flex items-center gap-4">
            <div class="w-16 h-16 bg-purple-100 rounded-xl flex items-center justify-center">
              <el-icon class="text-purple-600 text-2xl"><Star /></el-icon>
            </div>
            <div>
              <p class="text-2xl font-bold text-gray-900">{{ homeworkStats.graded }}</p>
              <p class="text-gray-600">已批改</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 作业列表 -->
      <div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
        <div class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
              <div class="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center">
                <el-icon class="text-white text-2xl"><Notebook /></el-icon>
              </div>
              <div>
                <h3 class="text-3xl font-bold text-gray-900">作业列表</h3>
                <p class="text-blue-600 text-xl">{{ classInfo?.className }} - 作业管理</p>
              </div>
            </div>
            <div class="flex items-center gap-3">
              <el-select v-model="filterStatus" placeholder="状态筛选" class="w-32">
                <el-option label="全部" value="" />
                <el-option label="未提交" value="no_submit" />
                <el-option label="已提交" value="submitted" />
              </el-select>
              <el-input v-model="searchKeyword" placeholder="搜索作业" class="w-48" clearable>
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </div>

        <div class="p-8">
          <!-- 加载状态 -->
          <div v-if="loading" class="text-center py-16">
            <el-icon class="is-loading text-blue-500 text-3xl mb-4"><Loading /></el-icon>
            <p class="text-gray-500 text-lg">正在加载作业数据...</p>
          </div>
          
          <div v-else class="space-y-6">
            <div v-for="homework in filteredHomeworkList" :key="homework.id" 
                 class="group p-6 border-2 border-gray-100 rounded-2xl hover:border-blue-300 hover:bg-blue-50 transition-all duration-300 cursor-pointer"
                 @click="viewHomeworkDetail(homework)">
              <div class="flex items-center justify-between">
                <div class="flex-1">
                  <div class="flex items-center gap-4 mb-4">
                    <h4 class="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors">
                      {{ homework.title }}
                    </h4>
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
                          :class="{
                            'bg-yellow-100 text-yellow-800': homework.submitCount === 0,
                            'bg-blue-100 text-blue-800': homework.submitCount > 0,
                            'bg-green-100 text-green-800': false
                          }">
                      {{ homework.submitCount === 0 ? '未提交' : `已提交(${homework.submitCount})` }}
                    </span>
                  </div>
                  <p class="text-gray-600 mb-3">{{ homework.content || homework.description }}</p>
                  <div class="flex items-center gap-6 text-sm text-gray-500">
                    <span>截止时间: {{ formatDate(homework.deadline) }}</span>
                    <span>创建时间: {{ formatDate(homework.createTime || homework.publishDate) }}</span>
                    <span v-if="homework.submitDate">提交时间: {{ formatDate(homework.submitDate) }}</span>
                    <span v-if="homework.score !== null">得分: {{ homework.score }}/{{ homework.totalScore }}</span>
                  </div>
                </div>
                <div class="flex items-center gap-3">
                  <el-button v-if="homework.submitCount === 0" 
                           type="primary" 
                           size="small" 
                           @click.stop="submitHomework(homework)"
                           class="rounded-full">
                    立即提交
                  </el-button>
                  <el-button v-if="homework.submitCount > 0" 
                           type="info" 
                           size="small" 
                           @click.stop="viewSubmission(homework)"
                           class="rounded-full">
                    查看提交
                  </el-button>
                  <el-icon class="text-gray-400 group-hover:text-blue-500 transition-colors">
                    <ArrowRight />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>

            <!-- 空状态 -->
            <div v-if="filteredHomeworkList.length === 0" class="text-center py-16">
              <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <el-icon class="text-gray-400 text-3xl"><Document /></el-icon>
              </div>
              <p class="text-gray-500 text-lg">暂无作业</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交作业对话框 -->
    <el-dialog v-model="showSubmitDialog" title="提交作业" width="600px" :close-on-click-modal="false">
      <el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="100px">
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="submitForm.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="作业描述" prop="description">
          <el-input v-model="submitForm.description" type="textarea" :rows="4" placeholder="请输入作业描述" />
        </el-form-item>
        <el-form-item label="附件上传" prop="attachments">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="submitForm.attachments"
            multiple
            drag
            class="w-full"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word、图片等格式，单个文件不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="submitForm.remarks" type="textarea" :rows="3" placeholder="可选：添加备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSubmitDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交作业</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 作业详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="作业详情" width="800px">
      <div v-if="selectedHomework" class="space-y-6">
        <div class="bg-gray-50 rounded-lg p-4">
          <h3 class="text-xl font-bold text-gray-900 mb-3">{{ selectedHomework.title }}</h3>
          <p class="text-gray-600 mb-4">{{ selectedHomework.description }}</p>
          <div class="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span class="text-gray-500">发布时间:</span>
              <span class="ml-2">{{ formatDate(selectedHomework.publishDate) }}</span>
            </div>
            <div>
              <span class="text-gray-500">截止时间:</span>
              <span class="ml-2">{{ formatDate(selectedHomework.deadline) }}</span>
            </div>
            <div>
              <span class="text-gray-500">状态:</span>
              <span class="ml-2">{{ getStatusText(selectedHomework.status) }}</span>
            </div>
            <div v-if="selectedHomework.score !== null">
              <span class="text-gray-500">得分:</span>
              <span class="ml-2 text-green-600 font-bold">{{ selectedHomework.score }}/{{ selectedHomework.totalScore }}</span>
            </div>
          </div>
        </div>

        <!-- 提交内容 -->
        <div v-if="selectedHomework.submission" class="bg-blue-50 rounded-lg p-4">
          <h4 class="text-lg font-semibold text-gray-900 mb-3">提交内容</h4>
          <p class="text-gray-700 mb-3">{{ selectedHomework.submission.content }}</p>
          <div v-if="selectedHomework.submission.attachments && selectedHomework.submission.attachments.length > 0">
            <p class="text-gray-600 mb-2">附件:</p>
            <div class="flex flex-wrap gap-2">
              <div v-for="file in selectedHomework.submission.attachments" :key="file.name" 
                   class="flex items-center gap-2 bg-white px-3 py-2 rounded-lg border">
                <el-icon class="text-blue-500"><Document /></el-icon>
                <span class="text-sm text-gray-700">{{ file.name }}</span>
                <el-button type="text" size="small" @click="downloadFile(file)">
                  <el-icon><Download /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 评分反馈 -->
        <div v-if="selectedHomework.grade" class="bg-green-50 rounded-lg p-4">
          <h4 class="text-lg font-semibold text-gray-900 mb-3">评分反馈</h4>
          <div class="space-y-3">
            <div class="flex items-center gap-4">
              <span class="text-gray-600">总分:</span>
              <span class="text-2xl font-bold text-green-600">{{ selectedHomework.score }}/{{ selectedHomework.totalScore }}</span>
            </div>
            <div v-if="selectedHomework.grade.comments">
              <p class="text-gray-600 mb-2">评语:</p>
              <p class="text-gray-700 bg-white p-3 rounded-lg">{{ selectedHomework.grade.comments }}</p>
            </div>
            <div v-if="selectedHomework.grade.detailedScore">
              <p class="text-gray-600 mb-2">详细评分:</p>
              <div class="bg-white p-3 rounded-lg space-y-2">
                <div v-for="(score, item) in selectedHomework.grade.detailedScore" :key="item" 
                     class="flex justify-between items-center">
                  <span class="text-gray-700">{{ item }}</span>
                  <span class="text-gray-900 font-medium">{{ score }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { mockClassList } from '@/mock/classData'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, ArrowRight, Plus, Document, Check, Clock, Star, 
  Notebook, Search, UploadFilled, Download, Loading 
} from '@element-plus/icons-vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

const classId = computed(() => Number(route.params.id))
const classInfo = computed(() => mockClassList.find(c => c.id === classId.value))

// 作业统计数据
const homeworkStats = ref({
  total: 0,
  ungraded: 0,
  published: 0,
  graded: 0
})

// 作业列表数据
const homeworkList = ref([])

// 加载状态
const loading = ref(false)

// 筛选和搜索
const filterStatus = ref('')
const searchKeyword = ref('')

const filteredHomeworkList = computed(() => {
  let filtered = homeworkList.value

  if (filterStatus.value) {
    if (filterStatus.value === 'no_submit') {
      filtered = filtered.filter(hw => hw.submitCount === 0)
    } else if (filterStatus.value === 'submitted') {
      filtered = filtered.filter(hw => hw.submitCount > 0)
    }
  }

  if (searchKeyword.value) {
    filtered = filtered.filter(hw => 
      hw.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (hw.content || hw.description || '').toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  return filtered
})

// 提交作业相关
const showSubmitDialog = ref(false)
const submitting = ref(false)
const submitFormRef = ref()
const submitForm = ref({
  title: '',
  description: '',
  attachments: [],
  remarks: ''
})

const submitRules = {
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入作业描述', trigger: 'blur' }]
}

const handleFileChange = (file, fileList) => {
  submitForm.value.attachments = fileList
}

const handleFileRemove = (file, fileList) => {
  submitForm.value.attachments = fileList
}

const handleSubmit = async () => {
  try {
    await submitFormRef.value.validate()
    submitting.value = true
    
    // 模拟提交过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('作业提交成功！')
    showSubmitDialog.value = false
    
    // 重置表单
    submitForm.value = {
      title: '',
      description: '',
      attachments: [],
      remarks: ''
    }
    
    // 刷新作业列表
    await fetchHomeworks()
    
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 作业详情相关
const showDetailDialog = ref(false)
const selectedHomework = ref(null)

const viewHomeworkDetail = (homework) => {
  selectedHomework.value = homework
  showDetailDialog.value = true
}

const submitHomework = (homework) => {
  ElMessage.info('跳转到提交页面，由后端实现')
}

const viewSubmission = (homework) => {
  viewHomeworkDetail(homework)
}

const viewGrade = (homework) => {
  viewHomeworkDetail(homework)
}

const downloadFile = (file) => {
  ElMessage.info(`下载文件: ${file.name}，由后端实现`)
}

// 工具函数
const getStatusText = (status) => {
  const statusMap = {
    published: '已发布',
    ungraded: '未批改',
    graded: '已批改'
  }
  return statusMap[status] || status
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const goBack = () => router.back()

// API调用函数
const fetchHomeworks = async () => {
  try {
    loading.value = true
    console.log('正在获取作业列表...')
    
    const response = await axios.get(`http://localhost:8088/api/homeworks/getAllHomeworks?_t=${Date.now()}`, {
      timeout: 10000, // 10秒超时
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    })
    
    console.log('API响应:', response.data)
    
    // 根据您提供的数据格式，API返回的是直接的数组
    if (Array.isArray(response.data)) {
      homeworkList.value = response.data
      console.log('获取到作业列表:', homeworkList.value)
      
      // 根据实际数据结构计算统计数据
      // 由于API返回的数据没有status字段，我们根据submitCount来判断状态
      const stats = {
        total: homeworkList.value.length,
        ungraded: homeworkList.value.filter(hw => hw.submitCount > 0).length, // 有提交的
        published: homeworkList.value.length, // 所有作业都是已发布的
        graded: 0 // 暂时没有评分状态字段
      }
      homeworkStats.value = stats
      console.log('统计数据:', stats)
      
      ElMessage.success(`成功获取 ${homeworkList.value.length} 条作业记录`)
    } else if (response.data && response.data.success) {
      // 如果API返回格式是 {success: true, data: [...]}
      homeworkList.value = response.data.data || []
      console.log('获取到作业列表:', homeworkList.value)
      
      const stats = {
        total: homeworkList.value.length,
        ungraded: homeworkList.value.filter(hw => hw.submitCount > 0).length,
        published: homeworkList.value.length,
        graded: 0
      }
      homeworkStats.value = stats
      console.log('统计数据:', stats)
      
      ElMessage.success(`成功获取 ${homeworkList.value.length} 条作业记录`)
    } else {
      console.error('API返回格式不正确:', response.data)
      ElMessage.error('获取作业列表失败: 数据格式不正确')
    }
  } catch (error) {
    console.error('获取作业列表失败:', error)
    if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
      ElMessage.error('无法连接到服务器，请确认后端服务是否正常运行')
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接')
    } else {
      ElMessage.error('获取作业列表失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchHomeworks()
})
</script>

<style scoped>
@keyframes blob {
  0% { transform: translate(0px, 0px) scale(1); }
  33% { transform: translate(30px, -50px) scale(1.1); }
  66% { transform: translate(-20px, 20px) scale(0.9); }
  100% { transform: translate(0px, 0px) scale(1); }
}
.animate-blob { animation: blob 7s infinite; }
.animation-delay-2000 { animation-delay: 2s; }
.animation-delay-4000 { animation-delay: 4s; }

/* 自定义上传组件样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 120px;
}

:deep(.el-upload__tip) {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}
</style>

